package com.unlcn.ils.crsc.service.xml.util;

import com.google.common.collect.Lists;
import com.unlcn.ils.crsc.service.util.BaseException;
import org.dom4j.*;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.Arrays;
import java.util.List;

public class XmlUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(XmlUtil.class);

    public static Document parse(String path) throws DocumentException {
        SAXReader reader = new SAXReader();
        Document document = null;
        try {
            document = reader.read(path);
        } catch (DocumentException e) {
            throw new BaseException(e.getMessage());
        }
        return document;
    }

    /**
     *  得到所有的属性
     * @param filepath
     * @param xpath
     * @return
     */
    public static List<Attribute> getAttrLists(String filepath, String xpath){
        List<Attribute> lists = Lists.newArrayList();
        File file = new File(filepath);
        if (file.isDirectory()) {
            List<String> filelist = Arrays.asList(file.list());
            filelist.forEach(filename -> {
                try {
                    Document document = XmlUtil.parse(filepath + filename);
                    List<Node> list = document.selectNodes(xpath);
                    list.forEach(node -> {
                        if (node.getNodeType() == 1) {
                            Element element = (Element) node;
                            lists.addAll(element.attributes());
                        }
                    });
                } catch (DocumentException ex) {
                    LOGGER.error(ex.getMessage());
                }
            });
        }
        else{
            try {
                Document document = XmlUtil.parse(filepath);
                List<Node> list = document.selectNodes(xpath);
                list.forEach(node -> {
                    if (node.getNodeType() == 1) {
                        Element element = (Element) node;
                        lists.addAll(element.attributes());
                    }
                });
            } catch (DocumentException ex) {
                LOGGER.error(ex.getMessage());
            }
        }
        return lists;

    }
}
